{% extends 'layouts/base.html' %}

{% block title %} 新建文章 {% endblock title %}

{% block stylesheets %}
    <link href="{{ cdn_prev }}qexo-static@2.2.3/qexo/vditor/index.css" rel="stylesheet"/>
{% endblock stylesheets %}

{% block content %}

    <!-- Page content -->
    <div class="container-fluid">
        <div class="row">
            <div class="card col-md-8 px-0 ms-md-4" id="vditor-container">
                <div id="vditor"></div>
            </div>
            <div class="card col-md-3 ms-md-4">
                <a class="text-end position-absolute col-11 mt-3" style="cursor: pointer;
                color: #172b4d"
                   href="javascript:editSide()"><i class="fas
                   fa-pen"></i></a>
                <h5 class="mt-3">文章参数</h5>
                <hr class="my-2"/>
                <div id="sidebar-container"></div>
            </div>
        </div>
        <div class="row py-4">
            <div class="card ms-md-4 col-md-11" id="bottom-bar">
                <div class="col-12">
                    <input type="button" class="btn btn-sm float-end mt-3"
                           value="添加"
                           style="border: 1px solid #dee2e6;border-radius: .25rem;"
                           onclick="addBottomItem()">
                    <h5 class="mt-3"><i class="fas fa-cogs"></i> 其他参数</h5>
                    <hr class="my-2"/>
                    <div id="bottom-container">
                    </div>
                    <br>
                </div>
            </div>
        </div>

        <div class="modal fade" id="sidebarEditModal" tabindex="-1"
             aria-labelledby="sidebarModalLabel"
             aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content bg-white">
                    <div class="modal-header" style="border: none;">
                        <h5 class="modal-title" id="sidebarEditModalLabel">编辑侧边栏</h5>
                        <button type="button" data-bs-dismiss="modal"
                                aria-label="Close" style="box-sizing: content-box;width: 1em;height:
                            1em;padding: .25em;color: #8392ab;border: 0;border-radius: .375rem;
                            opacity: .5;background: none">
                            <span aria-hidden="true">×</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div id="side-form" onsubmit="return false;">
                            <div class="row">
                                <div class="col-2">
                                    <label class="form-control-label">搜索项</label>
                                </div>
                                <div class="col-4">
                                    <label class="form-control-label">描述</label>
                                </div>
                                <div class="col-6">
                                    <label class="form-control-label">图标</label>
                                </div>
                            </div>
                            <div id="side-form-container"></div>
                        </div>
                    </div>
                    <div class="modal-footer" style="border: none;">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消
                        </button>
                        <button type="button" class="btn btn-primary" data-bs-dismiss="modal"
                                onclick="applySide()">确定
                        </button>
                    </div>
                </div>
            </div>
        </div>

        {% include "includes/footer.html" %}

    </div>

{% endblock content %}

<!-- Specific JS goes HERE -->
{% block javascripts %}
    <script src="{{ cdn_prev }}vditor@3.9.4/dist/index.min.js"></script>


    <script>
        var _status = true, front_matter = {{ front_matter|safe }}, categories, tags;
        var file_content = "";

        $.ajaxSetup({
            data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
        });

        function set_vditor_size() {
            let height = $("#vditor-container").height();
            if (height < document.documentElement.clientHeight - 25) {
                height = document.documentElement.clientHeight - 25;
            }
            $("#vditor").css({
                "height": height + "px", "width":
                    "auto"
            });
            if (checkIfDark()) {
                vditor.setTheme('dark', 'dark', 'native');
            }
        }

        $.ajaxSetup({
            data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
        });


        function Publish() {
            if (!$("input[name='filename']").val()) {
                notyf.error("请输入正确的文章名！");
            } else {
                if (!_status) {
                    return false;
                }
                let loading = new KZ_Loading('正在发布中...');
                let nextstep = function () {
                    _status = false;
                    loading.show();
                    $.ajax({
                        url: '/api/save_post/',
                        method: 'post',
                        data: {
                            "file": $("input[name='filename']").val(),
                            "content": vditor.getValue(),
                            "front_matter": JSON.stringify(get_front_matter())
                        },
                        dataType: 'JSON',
                        success: function (res) {
                            loading.destroy();
                            if (res.status) {
                                notyf.success(res.msg + '等待转跳...');
                                file_content = vditor.getValue();
                                setTimeout(window.location.href = "edit.html?file=" +
                                    encodeURIComponent(res.path)
                                    + "&postname=" +
                                    encodeURIComponent($("input[name='filename']").val()), 1000);
                            } else {
                                notyf.error(res.msg);
                            }
                            _status = true;
                        },
                        error: function (res) {
                            loading.destroy();
                            notyf.error("网络错误！");
                            _status = true;
                        }
                    })
                }
                if (excerpt_config.auto !== "关闭") excerpt_post(nextstep);
                else nextstep();
            }
        }

        function SaveDraft() {
            if (!$("input[name='filename']").val()) {
                notyf.error("请输入正确的文章名！");
            } else {
                if (!_status) {
                    return false;
                }
                var loading = new KZ_Loading('等待转跳...');
                let nextstep = function () {
                    _status = false;
                    loading.show();
                    $.ajax({
                        url: '/api/save_draft/',
                        method: 'post',
                        data: {
                            "file": $("input[name='filename']").val(),
                            "content": vditor.getValue(),
                            "front_matter": JSON.stringify(get_front_matter())
                        },
                        dataType: 'JSON',
                        success: function (res) {
                            loading.destroy();
                            if (res.status) {
                                notyf.success('草稿保存成功！等待转跳...');
                                file_content = vditor.getValue();
                                setTimeout(window.location.href = "edit.html?file=" +
                                    encodeURIComponent(res.path)
                                    + "&postname=" +
                                    encodeURIComponent($("input[name='filename']").val()), 1000);
                            } else {
                                notyf.error(res.msg);
                            }
                            _status = true;
                        },
                        error: function (res) {
                            loading.destroy();
                            notyf.error("网络错误！");
                            _status = true;
                        }
                    })
                }
                if (excerpt_config.auto === "总是截取") excerpt_post(nextstep);
                else nextstep();
            }
        }


        function fIsMobile() {
            return /Android|iPhone|iPad|iPod|BlackBerry|webOS|Windows Phone|SymbianOS|IEMobile|Opera Mini/i.test(navigator.userAgent);
        }

        //挂载到全局
        if (fIsMobile()) {
            window.vditor = new Vditor('vditor', {
                after(d) {
                    file_content = vditor.getValue();
                    showSidebar(true);
                },
                toolbarConfig: {
                    pin: true
                },
                counter: {
                    enable: true
                },
                "cdn": "{{ cdn_prev }}vditor@3.9.4",
                "mode": "wysiwyg",
                "height": window.innerHeight * 0.75,
                {% if file_content %}
                    "value": {{ file_content|safe }},
                {% endif %}
                "fullscreen": {
                    "index": 1050,
                },
                "debugger": false,
                "cache": {
                    "enable": false,
                }, "preview": {
                    "theme": {
                        "path": "{{ cdn_prev }}vditor@3.9.4/dist/css/content-theme"
                    }
                },
                toolbar: [
                    'emoji',
                    'link',
                    {% if img_bed %}
                        {
                            name: "upload",
                            tip: '上传图片',
                        },
                    {% endif %}
                    'edit-mode',
                    {
                        name: 'more',
                        toolbar: [
                            'insert-after',
                            'fullscreen',
                            'preview',
                            'info',
                            'help',
                        ],
                    },
                ], hint: {
                    emoji: {{ emoji|safe }}
                },
                // 文件上传配置
                upload: {
                    accept: "image/*",
                    url: "/api/upload/",
                    max: 100 * 1024 * 1024,
                    filename(name) {
                        return name
                            .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
                            .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
                            .replace("/\\s/g", "");
                    },
                    success(editor, msg) {
                        let responseData = JSON.parse(msg)
                        if (responseData.status) {
                            let imageUrl = responseData.url;
                            let succFileText = "";
                            if (vditor && vditor.vditor.currentMode === "wysiwyg") {
                                succFileText += `\n <img alt=${imageUrl} src="${imageUrl}">`;
                            } else {
                                succFileText += `\n![${imageUrl}](${imageUrl})`;
                            }
                            //将图片路径写入文本
                            document.execCommand("insertHTML", false, succFileText);
                            notyf.success(responseData.msg);
                        } else {
                            notyf.error(responseData.msg);
                        }

                    },
                    error() {
                        notyf.error("上传失败！");
                    }
                },
            })
        } else {
            window.vditor = new Vditor("vditor", {
                after(d) {
                    file_content = vditor.getValue();
                    showSidebar(true);
                },
                // 获取焦点方法
                focus(md) {
                    document.onkeydown = function () {
                        // 判断 Ctrl+S
                        if (event.ctrlKey === true && event.keyCode === 83) {
                            SaveDraft();
                            event.preventDefault();
                        }
                    }
                },
                // _lutePath: "lib/vditor-3.7.3/src/js/lute/lute.min.js",
                // 这个是自定义导航栏
                "toolbar": [
                    "emoji",
                    "headings",
                    "bold",
                    "italic",
                    "strike",
                    "link",
                    "|",
                    "list",
                    "ordered-list",
                    "check",
                    "|",
                    "quote",
                    "line",
                    "code",
                    "inline-code",
                    "|",
                    {% if img_bed %}
                        {
                            name: "upload",
                            tip: '上传图片',
                        },
                    {% endif %}
                    "table",
                    "export",
                    "|",
                    "fullscreen",
                    "edit-mode",
                    "preview"
                ],
                "cdn": "{{ cdn_prev }}vditor@3.9.4",
                "fullscreen": {
                    "index": 1050,
                },
                "height": $("#vditor-container").height(),
                "cache": {
                    "enable": false
                },
                "mode": "ir",
                "debugger": false,
                "preview": {
                    "mode": "both",
                    "theme": {
                        "path": "{{ cdn_prev }}vditor@3.9.4/dist/css/content-theme"
                    }
                }, hint: {
                    emoji: {{ emoji|safe }}
                },
                {% if file_content %}
                    "value": {{ file_content|safe }},
                {% endif %}
                // 文件上传配置
                upload: {
                    accept: "image/*",
                    url: "/api/upload/",
                    max: 100 * 1024 * 1024,
                    filename(name) {
                        return name
                            .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
                            .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
                            .replace("/\\s/g", "");
                    },
                    success(editor, msg) {
                        let responseData = JSON.parse(msg)
                        if (responseData.status) {
                            let imageUrl = responseData.url;
                            let succFileText = "";
                            if (vditor && vditor.vditor.currentMode === "wysiwyg") {
                                succFileText += `\n <img alt=${imageUrl} src="${imageUrl}">`;
                            } else {
                                succFileText += `\n![${imageUrl}](${imageUrl})`;
                            }
                            //将图片路径写入文本
                            document.execCommand("insertHTML", false, succFileText);
                            notyf.success(responseData.msg);
                        } else {
                            notyf.error(responseData.msg);
                        }

                    },
                    error() {
                        notyf.error("上传失败！");
                    }
                },
            });
        }

        window.onbeforeunload = function (e) {
            e = e || window.event;
            if (e && file_content !== vditor.getValue()) {
                e.returnValue = '确定要离开吗?';
                return '确定要离开吗?';
            }
        }


        var OrgSidebar = {{ sidebar|safe }};
        var Sidebar = [...OrgSidebar];

        function showEditSide() {
            let html = "";
            if (!Sidebar.length) {
                Sidebar = [{"search": "", "name": "", "icon": ""}];
            }
            let color = checkIfDark() ? "bg-gradient-dark text-white" : "bg-white text-dark";
            for (let i = 0; i < Sidebar.length; i++) {
                html += `<form class="row" id="side-row-${i}">
                                <div class="col-2">
                                    <input type="text" class="form-control ${color}" name="search"
                                           placeholder="冒号前的内容" value="${Sidebar[i].search}">
                                </div>
                                <div class="col-4">
                                    <input type="text" class="form-control ${color}" name="name"
                                           placeholder="描述标题" value="${Sidebar[i].name}">
                                </div>
                                <div class="col-6">
                                    <div class="input-group">
                                        <input type="text" class="form-control ${color}" name="icon"
                                               placeholder="使用的图标"  value="${Sidebar[i].icon}">
                                        <button class="btn mb-0 childButton" type="button"
                                                onclick="newSideItem(${(i + 1).toString()})">
                                            +
                                        </button>
                                        <button class="btn mb-0 childButton" type="button"
                                                onclick="delSideItem(${i})">
                                            -
                                        </button>
                                    </div>
                                </div>
                            </form>`;
            }
            $("#side-form-container").html(html);
        }

        function editSide() {
            Sidebar = [...OrgSidebar];  // 拷贝数组
            showEditSide();
            $('#sidebarEditModal').modal('show');
        }

        function newSideItem(i) {
            saveSideItems();
            Sidebar.splice(i, 0, {"search": "", "name": "", "icon": ""});
            showEditSide();
        }

        function saveSideItems() {
            let tmp;
            for (let i = 0; i < Sidebar.length; i++) {
                tmp = $("#side-row-" + i).serializeArray();
                for (let j = 0; j < tmp.length; j++) {
                    Sidebar[i][tmp[j].name] = tmp[j].value;
                }
            }
            return Sidebar;
        }

        function delSideItem(i) {
            saveSideItems();
            Sidebar.splice(i, 1);
            showEditSide();
        }

        function applySide() {
            saveSideItems();
            for (let i = 0; i < Sidebar.length; i++) {
                if (Sidebar[i].search === "") {
                    Sidebar.splice(i, 1);
                    i--;
                }
            }
            let loading = new KZ_Loading('边栏保存中...');
            loading.show();
            $.ajax({
                url: '/api/set_sidebar/',
                method: 'post',
                data: {
                    "type": "post", "content": JSON.stringify(Sidebar)
                },
                dataType: 'JSON',
                success: function (res) {
                    loading.destroy();
                    if (res.status) {
                        notyf.success('保存成功！');
                        showSidebar();
                    } else {
                        notyf.error('保存失败！');
                    }
                },
                error: function (res) {
                    loading.destroy();
                    notyf.error("网络错误！");
                }
            })
        }

        if (typeof (front_matter["tags"]) === "object" && front_matter["tags"] !==
            null) tags = front_matter["tags"];
        else if (typeof (front_matter["tags"]) === "string") tags = [front_matter["tags"]];
        else tags = [];
        if (typeof (front_matter["categories"]) === "object" && front_matter["categories"] !==
            null) categories =
            front_matter["categories"];
        else if (typeof (front_matter["categories"]) === "string") categories = [front_matter["categories"]];
        else categories = [];

        trimSpace(categories);
        trimSpace(tags);

        function show_tags() {
            let html = "";
            for (let i = 0; i < tags.length; i++) {
                html += `<span class="px-1 py-0-5 text-xs select-none
                            d-inline-block  rounded-pill me-1 mb-0.5"
                            style="color: rgb(255, 255, 255); background-color: rgb(52, 152, 219);"
                            onclick="del_tag(this.innerText);">` + tags[i]
                    + `</span>`;
            }
            $("#tag-container").html(html);
            set_vditor_size();
        }

        function add_tag(name) {
            if (!name) {
                return;
            }
            if (tags.includes(name)) {
                notyf.error("标签已存在! ");
            } else {
                tags.push(name);
                show_tags();
            }
        }

        function del_tag(name) {
            for (let i = 0; i < tags.length; i++) {
                if (String(tags[i]) === String(name)) {
                    tags.splice(i, 1);
                }
            }
            $("#qexo-tag").val(String(name));
            show_tags();
        }

        function show_categories() {
            let html = "";
            for (let i = 0; i < categories.length; i++) {
                html += `<span class="px-1 py-0-5 text-xs select-none
                            d-inline-block  rounded-pill me-1 mb-0.5"
                            style="color: rgb(255, 255, 255); background-color: rgb(52, 152, 219);
                            " onclick="del_category(this.innerText);">` + ((typeof categories[i]
                        === "object") ? categories[i][0] : categories[i]) +
                    `</span>`;
            }
            $("#category-container").html(html);
            set_vditor_size();
        }

        function add_category(name) {
            if (!name) {
                return;
            }
            for (let i = 0; i < categories.length; i++) {
                if (String(typeof (categories[i]) === "object" ? categories[i][0] : categories[i]) === name) {
                    notyf.error("分类已存在! ");
                    return;
                }
            }
            categories.push("{{ config.name }}" === "Hexo" ? [name] : name);
            show_categories();
        }

        function del_category(name) {
            for (let i = 0; i < categories.length; i++) {
                if (String(typeof (categories[i]) === "object" ? categories[i][0] : categories[i]) === String(name)) {
                    categories.splice(i, 1);
                }
            }
            $("#qexo-category").val(String(name));
            show_categories();
        }


        function get_front_matter() {
            let custom = {...save_bottom()};
            delete custom[""];
            for (let i = 0; i < OrgSidebar.length; i++) {
                if (OrgSidebar[i]["search"] === "tags") {
                    custom["tags"] = tags;
                } else if (OrgSidebar[i]["search"] === "categories") {
                    custom["categories"] = categories;
                } else {
                    let tmp = $("#" + OrgSidebar[i]["search"]).val();
                    if (tmp === "true") {
                        custom[OrgSidebar[i]["search"]] = true;
                    } else if (tmp === "false") {
                        custom[OrgSidebar[i]["search"]] = false;
                    } else if (tmp === "null") {
                        custom[OrgSidebar[i]["search"]] = null;
                    } else {
                        custom[OrgSidebar[i]["search"]] = tmp;
                    }
                }
            }
            return custom;
        }

        function showSidebar(first = false) {
            let html = "", content, front = front_matter, ifTag = false, ifCategory = false;
            if (!first) {
                front = get_front_matter();
                save_bottom();
                OrgSidebar = [...Sidebar];
            }
            for (let i = 0; i < OrgSidebar.length; i++) {
                if (OrgSidebar[i]["search"] === "tags") {
                    html += `<div class="form-group">
                        <label class="form-control-label"><i class="${OrgSidebar[i]["icon"]}"></i>${OrgSidebar[i]["name"]}</label>
                        <div class="input-group mb-0">
                          <input type="text" class="form-control" placeholder="添加标签" name="qexo-tag" id="qexo-tag">
                          <button class="btn mb-0 childButton" type="button" onclick="add_tag($('#qexo-tag')
                          .val());$('#qexo-tag').val('')">+</button>
                        </div>
                        <div id="tag-container"></div>
                    </div>`;
                    ifTag = true;
                } else if (OrgSidebar[i]["search"] === "categories") {
                    html += `<div class="form-group">
                        <label class="form-control-label"><i class="${OrgSidebar[i]["icon"]}"></i>${OrgSidebar[i]["name"]}</label>
                        <div class="input-group mb-0">
                          <input type="text" class="form-control" placeholder="添加分类" name="qexo-category" id="qexo-category">
                          <button class="btn mb-0 childButton" type="button" onclick="add_category($
                          ('#qexo-category').val());$('#qexo-category').val('')">+</button>
                        </div>
                        <div id="category-container"></div>
                    </div>`;
                    ifCategory = true;
                } else {
                    if (OrgSidebar[i]["search"] === "updated" || OrgSidebar[i]["search"] === "lastmod") {
                        content = getRFC3339();
                    } else if (front[OrgSidebar[i]["search"]] !== undefined) {
                        content = front[OrgSidebar[i]["search"]];
                    } else content = "";
                    content = (typeof content) === "object" ? JSON.stringify(content).replaceAll("\"", "&quot;") : content.toString().replaceAll("\"", "&quot;")
                    html += `<div class="form-group">
                        <label class="form-control-label"><i class="` + OrgSidebar[i]["icon"]
                        + `"></i> ` + OrgSidebar[i]["name"] + `</label>
                        <input type="text" name="title"
                               class="form-control"
                               placeholder="` + OrgSidebar[i]["name"] + `"
                               id="` + OrgSidebar[i]["search"] + `"
                               value="` + content + `"></div>`;
                }
                delete front[OrgSidebar[i]["search"]];
            }
            $("#sidebar-container").html(html);
            if (ifTag) show_tags();
            if (ifCategory) show_categories();
            front_matter = front;
            show_bottom();
            set_vditor_size();
            // 监听分类、标签回车键
            $('#qexo-tag').bind('keypress', function (event) {
                if (event.keyCode === 13) {
                    event.preventDefault();
                    add_tag($('#qexo-tag').val());
                    $('#qexo-tag').val('')
                }
            });
            $('#qexo-category').bind('keypress', function (event) {
                if (event.keyCode === 13) {
                    event.preventDefault();
                    add_category($('#qexo-category').val());
                    $('#qexo-category').val('')
                }
            });
        }

        function save_bottom() {
            let tmp;
            let keys = Object.keys(front_matter);
            front_matter = {};
            for (let i = 0; i < keys.length; i++) {
                tmp = $("#bottom-row-" + i).serializeArray();
                try {
                    front_matter[tmp[0].value] = JSON.parse(tmp[1].value);
                } catch (e) {
                    front_matter[tmp[0].value] = tmp[1].value;
                }
            }
            return front_matter;
        }

        function delBottomItem(i) {
            save_bottom();
            let keys = Object.keys(front_matter);
            delete front_matter[keys[i]];
            show_bottom();
        }

        function addBottomItem() {
            save_bottom();
            if (front_matter[""] !== "") front_matter[""] = "";
            show_bottom();
        }

        function show_bottom() {
            let html = "";
            let keys = Object.keys(front_matter);
            if (keys.length === 0) {
                $("#bottom-container").html("暂无其他参数");
                return;
            }
            html = `<div class="row">
                        <div class="col-2">
                            <label class="form-control-label">标头</label>
                        </div>
                        <div class="col-4">
                            <label class="form-control-label">内容</label>
                        </div>
                    </div>`
            for (let i = 0; i < keys.length; i++) {
                html += `<form class="row" id="bottom-row-${i}">
                                <div class="col-2">
                                    <input type="text" class="form-control" name="search"
                                           placeholder="冒号前的内容" value="${escapeString(keys[i])}">
                                </div>
                                <div class="col-10">
                                    <div class="input-group">
                                        <input type="text" class="form-control" name="icon"
                                               placeholder="若有多级, 请使用JSON格式"  value="` +
                    escapeString(typeof (front_matter[keys[i]]) === "object" ? JSON.stringify
                    (front_matter[keys[i]]) : front_matter[keys[i]]) + `">

                                            <button class="btn mb-0 childButton" type="button"
                                                    onclick="delBottomItem(${i})">
                                                -
                                            </button>
                                    </div>
                                </div>
                            </form>`;
            }
            $("#bottom-container").html(html);
        }
    </script>
    {% include "includes/editor-scripts.html" %}
{% endblock javascripts %}